import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:interview/components/page/page_load_overlay.dart';
import 'package:interview/components/page/page_nav_bar.dart';
import 'package:interview/components/status_bar_warpper.dart';
import 'package:interview/controller/interview_details_controller.dart';
import 'package:interview/controller/question_details_controller.dart';
import 'package:interview/pages/question/components/question_content.dart';
import 'package:interview/providers/app_refresh_providers.dart';
import 'package:interview/servers/question_detail.dart';
import 'package:interview/theme/app_colors.dart';
import 'package:interview/utils/logger.dart';
import 'package:provider/provider.dart';

class QuestionPage extends StatefulWidget {
  final String id;
  final List<String> ids;
  final int typeId;
  final int views;
  final String? tab;
  const QuestionPage({
    super.key, 
    required this.id, 
    required this.ids, 
    required this.typeId,
    required this.views,
    this.tab
  });

  @override
  State<QuestionPage> createState() => _QuestionPageState();
}

class _QuestionPageState extends State<QuestionPage> {
  late PageController _pageController;
  late int initialIndex;
  final QuestionDetailsController _questionDetailsController = Get.put(QuestionDetailsController()); // 持久化 permanent: true  不推荐在这里用 会造成内存泄漏
  final InterviewDetailsController _interviewDetailsController = Get.put(InterviewDetailsController());
  bool isHorizontalGesture = false; // 是否为水平滑动手势
  double horizontalDragDistance = 0; // 水平滑动距离
  double startX = 0; // 滑动起点的 X 坐标
  double startY = 0; // 滑动起点的 Y 坐标

  @override
  void initState() {
    super.initState();
    initialIndex = widget.ids.indexOf(widget.id);
    _pageController = PageController(initialPage: initialIndex);
    _loadQuestionData(initialIndex);
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  /// 加载指定索引的问题详情
  Future<void> _loadQuestionData(int index) async {
    if (index < 0 || index >= widget.ids.length) return; // 处理边界

    final String id = widget.ids[index]; // 根据索引找到题目ID
    
    // 根据 widget.tab 的是否为空，选择对应的 Controller
    final bool useQuestionController = widget.tab!.isEmpty;
    final dynamic controller = useQuestionController? _questionDetailsController  : _interviewDetailsController;

    // 检查是否已有数据，避免重复请求
    final isHas = controller.checkDetail(widget.views, id);
    if (isHas) {
      Logger.info('详情已存在，跳过请求: $id', tag: "_loadQuestionData");
      return;
    }

    final progressNotifier = ValueNotifier<double>(0.0);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      PageLoadOverlay.show(context: context);
    });

    try {
      // 加载详情的逻辑
      await controller.loadQuestionDetail(
        widget.views,
        widget.typeId,
        id,
        () => getQuestionDetail(id, context),
      );
    } catch (e , stackTrace) {
      Logger.error('_loadQuestionData 报错 $e', tag: "接口请求失败" , stackTrace:stackTrace );
    } finally {
      progressNotifier.dispose();
      WidgetsBinding.instance.addPostFrameCallback((_) {
        PageLoadOverlay.hide();
      });
    }
  }

  /// 构建手势监听器  PageView + WebView 手势冲突的解决方案： Listener 进行监听而不是进行拦截 手势事件
  Widget _buildGestureListener(BuildContext context, Widget child) {
    return Listener(
      onPointerDown: _handlePointerDown,
      onPointerMove: _handlePointerMove,
      onPointerUp: _handlePointerUp,
      child: child,
    );
  }

  /// 处理手指按下事件
  void _handlePointerDown(PointerDownEvent event) {
    startX = event.position.dx;
    startY = event.position.dy;
    horizontalDragDistance = 0;
    isHorizontalGesture = false;
  }

  /// 处理手指移动事件
  void _handlePointerMove(PointerMoveEvent event) {
    double deltaX = event.position.dx - startX;
    double deltaY = event.position.dy - startY;
    if (!isHorizontalGesture && deltaX.abs() > deltaY.abs()) {
      isHorizontalGesture = true;
    }
    if (isHorizontalGesture) {
      horizontalDragDistance = deltaX;
    }
  }

  /// 处理手指抬起事件
  void _handlePointerUp(PointerUpEvent event) {
    if (isHorizontalGesture) {
      if (horizontalDragDistance.abs() > 120) {
        if (horizontalDragDistance < 0) {
          _goToNextPage();
        } else if (horizontalDragDistance > 0) {
          _goToPreviousPage();
        }
        _loadQuestionData(initialIndex);
      }
    }
    horizontalDragDistance = 0;
  }

  /// 跳转到下一页
  void _goToNextPage() {
    if (initialIndex < widget.ids.length - 1) {
      _pageController.nextPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
      initialIndex++;
    }
  }

  /// 跳转到上一页
  void _goToPreviousPage() {
    if (initialIndex > 0) {
      _pageController.previousPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
      initialIndex--;
    }
  }

  /// 构建页面内容
  Widget _buildPageContent(BuildContext context ) {
    final theme = Theme.of(context).extension<AppColors>()!;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        PageNavBar(
          theme: theme,
          showTitle: true,
          title: widget.tab!.isEmpty ? "试题详情" :"面经详情",
          showRight: false,
        ),
        Expanded(
          child: PageView.builder(
            key: const PageStorageKey('QuestionPageView'),
            controller: _pageController,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: widget.ids.length,
            onPageChanged: (index) {
              if (initialIndex != index) {
                initialIndex = index;
                _loadQuestionData(index);
              }
            },
            itemBuilder: (context, index) {
              final id = widget.ids[index];
              return Obx(() {
                final bool useQuestionController = widget.tab!.isEmpty;
                final dynamic controller = useQuestionController? _questionDetailsController  : _interviewDetailsController;
                final detail = controller.getQuestionDetail(id);
                if (detail == null) {
                  return const SizedBox.shrink();
                }
                return QuestionContent(
                  theme: theme,
                  typeId:widget.typeId,
                  questionDetail: detail,
                  ids:widget.ids,
                  tab: widget.tab ?? '',
                );
              });
            },
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).extension<AppColors>()!;
    return Consumer<AppRefreshProvider>(
      builder: (context , refreshNotifier , child){
        if(refreshNotifier.shouldRefresh && mounted){
          // 延迟执行数据加载，避免在构建过程中直接调用
          WidgetsBinding.instance.addPostFrameCallback((_) {
            _loadQuestionData(initialIndex).then((_){
              refreshNotifier.resetRefresh(); // 重置刷新标志
            });
          });
        }
        return StatusBarWrapper(
          statusBarColor: theme.subjectPure!,
          statusBarIconBrightness: Theme.of(context).brightness == Brightness.dark? Brightness.light: Brightness.dark,
          child: Scaffold(
            appBar: null,
            body: SafeArea(
              child: _buildGestureListener(
                context,
                Container(
                  color: theme.subjectPure,
                  child: _buildPageContent(context)
                ),
              ),
            ),
          ),
        );
      }
    );
  }
}
